"use client";
import { UserOutlined } from "@ant-design/icons";
import { Bubble, BubbleProps, Sender, XStream } from "@ant-design/x";
import { Flex, Tag, Typography } from "antd";
import React, { useState, useEffect, useMemo } from "react";
import "./index.scss";
import { userControllerUpdateUser } from "@/app/servers/api/user";
import markdownit from "markdown-it";
import { baseUrl } from "@/app/servers/utils/request";

const md = markdownit({ html: true, breaks: true });
const renderMarkdown: BubbleProps["messageRender"] = (content) => (
  <Typography>
    {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
    <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
  </Typography>
);

const fooAvatar: React.CSSProperties = {
  color: "#f56a00",
  backgroundColor: "#fde3cf",
};

export interface ConservationProps {
  userInfo: API.GetUserInfoDto;
  promptTextList: string[];
}

const colors = [
  "magenta",
  "red",
  "volcano",
  "orange",
  "gold",
  "lime",
  "green",
  "cyan",
  "blue",
  "geekblue",
  "purple",
];
const Conservation: React.FC<ConservationProps> = ({
  userInfo,
  promptTextList,
}) => {
  const [inputValue, setInputValue] = useState("早上好");
  const [loading, setLoading] = useState<boolean>(false);

  const [messageList, setMessageList] = useState<API.ChatMessage[]>(
    userInfo?.chatRecords
      ? JSON.parse(userInfo.chatRecords)
      : [
          {
            role: "system",
            content: "你好，我是珊瑚保护智能小助手，请问有什么问题要问我吗？",
          },
        ]
  );

  const getRandomColor = () => {
    return colors[Math.floor(Math.random() * colors.length)];
  };

  const handleSuggestionClick = (word: string) => {
    setInputValue(word);
  };

  const scrollToBottom = () => {
    const chatContainer = document.querySelector(".overflow-auto.relative.z-0");
    if (chatContainer) {
      chatContainer.scrollTo({
        top: chatContainer.scrollHeight,
        behavior: "smooth",
      });
    }
  };

  useEffect(() => {
    const timer = setTimeout(scrollToBottom, 100);
    return () => clearTimeout(timer);
  }, []);

  useEffect(() => {
    const timer = setTimeout(scrollToBottom, 100);
    return () => clearTimeout(timer);
  }, [messageList]);

  const queryDouBao = async () => {
    setLoading(true);

    const requestData: API.ChatMessage[] = [
      ...messageList,
      { role: "user", content: inputValue },
      {
        role: "system",
        content: "",
      },
    ];
    const token = localStorage.getItem("token");
    // 先插入自己的发言
    setMessageList([...requestData]);
    // 清空输入框
    setInputValue("");
    const res = await fetch(baseUrl + "/api/gpt", {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ content: requestData }),
      method: "POST",
    });
    let msg = "";
    for await (const chunk of XStream({
      readableStream: res.body!,
    })) {
      const newMsg = JSON.parse(chunk.data)?.data;
      msg += newMsg;
      requestData.at(-1)!.content = msg;
      setMessageList([...requestData]);
      setTimeout(scrollToBottom, 100);
    }
    setLoading(false);
    await userControllerUpdateUser({
      id: userInfo.id,
      chatRecords: JSON.stringify(requestData),
    });
  };

  const SuggestionWords = useMemo(() => {
    return promptTextList.map((word, index) => (
      <Tag
        key={index}
        color={getRandomColor()}
        className="cursor-pointer"
        onClick={() => handleSuggestionClick(word)}
      >
        {word}
      </Tag>
    ));
  }, [promptTextList]);
  return (
    <div
      className="p-4 pb-0 overflow-auto hide-scrollbar"
      style={
        {
          height: "calc(100vh - 205px)",
          "--scroll-bar-background": "transparent",
          scrollbarWidth: "none",
          msOverflowStyle: "none",
        } as React.CSSProperties
      }
    >
      <Flex
        className="overflow-auto relative z-0 hide-scrollbar"
        gap="middle"
        vertical
        style={{ maxHeight: "calc(100vh - 300px)" }}
      >
        {messageList.map((el, index) => {
          return (
            <Bubble
              placement={el.role === "user" ? "end" : "start"}
              content={el.content}
              avatar={{ icon: <UserOutlined />, style: fooAvatar }}
              key={index}
              messageRender={renderMarkdown}
            />
          );
        })}
      </Flex>
      <div className="fixed bottom-0 left-0 p-4 w-full z-10 bg-white">
        <Flex vertical gap="middle">
          <div className="flex flex-wrap gap-2 ">{SuggestionWords}</div>
          <Sender
            loading={loading}
            value={inputValue}
            onChange={(v) => {
              setInputValue(v);
            }}
            onSubmit={() => {
              queryDouBao();
            }}
          />
        </Flex>
      </div>
    </div>
  );
};
export default Conservation;
